#!/usr/bin/env python
#coding:utf-8

'''
This py script is used to compile online branch code and update package make!
Created on 2016.10.13
Author:yoya
'''

import os
import re
import time
import shutil
import ConfigParser
import xml.dom.minidom
from xml.etree import ElementTree as ET

cf = ConfigParser.ConfigParser()
cf_file = "maven.conf"
cf.read(cf_file)
exePath = os.path.abspath('.')
upTime = int(time.strftime('%Y%m%d%H%M'))

def inputProj():
    '''read input project which will be update!'''
    cfgSec = cf.sections()
    mainProjList = []
    srvProjList = []
    for i in cfgSec:
        if i != 'svnInfo':
            if cf.get(i, 'type') == 'main':
                mainProjList.append(i)
            elif cf.get(i, 'type') == 'srv':
                srvProjList.append(i)
            else:
                print "ERROR project type: %s ,please check" %(i)
    print "Main List:\n%s" %(mainProjList)
    #print "Srv List:\n%s" %(srvProjList)
    iput = raw_input('请输入更新的项目(多个项目用逗号隔开):')
    projListTmp = iput.split(',')
    inputMain = []
    inputSrv = []
    inputAll = []
    for i in projListTmp:
        if i.strip() in mainProjList:
            inputMain.append(i.strip())
            inputAll.append(i.strip())
        elif i.strip() in srvProjList:
            inputSrv.append(i.strip())
            inputAll.append(i.strip())
        else:
            print "Error,Please check the project name: %s" %i
            raw_input('项目不存在,按回车键退出...')
            exit(1)
    return (inputMain, inputSrv,inputAll)

def Compile():
    '''compile the java files with maven!'''   
    try:
        os.chdir(cf.get('svnInfo','svnPath'))
        os.system('svn update')
        os.system('mvn install')
    except:
        raw_input('编译命令执行出错！按回车键退出...')
        exit(1)
        
def mkPkgDir():
    '''create update package's directory!'''
    os.chdir(os.path.join(exePath,'Package'))
    a = 1
    while True:
        pkgName = time.strftime('%Y%m%d')+'-%s' %a
        if os.path.exists(pkgName):
            a += 1
            continue
        else:
            os.makedirs(pkgName)
            os.chdir(pkgName)
            break
    pkgDir = os.path.join(exePath,'Package',pkgName)
    return pkgDir
    

class pkgMake:
    def __init__(self,projName):
        self.projName = projName
        self.projSvnName = cf.get(projName,'svnName')
        
    def svnVer(self):
        '''read svn version which will begain to extract! '''
        while True:
            svnVersion = raw_input('请输入%s更新的起始版本号: ' %self.projSvnName ).strip()
            try:
                svnVersion = int(svnVersion)
            except:
                print "对不起,输入有误!"
                continue
            
            codePath = os.path.join(cf.get('svnInfo','svnPath'),self.projSvnName,'src','main')
            os.chdir(codePath)
            xmlFile = os.path.join(exePath,'tmp','tmp.xml')
            os.system('echo > %s' %(xmlFile))
            try:
                '''get svn log and put it into xml file'''
                endVersion = cf.get(self.projName,'endVersion')
                os.system('svn diff --xml -r %s:%s --summarize > %s' %(svnVersion,endVersion,xmlFile))
                
                '''analyse the xml file'''
                dom = xml.dom.minidom.parse(xmlFile)
                root = dom.documentElement
                itemlist = root.getElementsByTagName('path')
            except:
                print "版本号或svn配置信息有误!"
                continue
            break
        
        '''extract the java file and static file !'''
        fList = []
        javaList = []
        staticList = []
        for i in itemlist:
            fList.append(i.firstChild.data)
        for i in fList:
            try:
                if i.endswith('.java'):
                    javaList.append(i)
                elif i.startswith('webapp'):
                    if os.path.isfile(i):
                        staticList.append(i)
            except AttributeError:
                pass               
       
        '''copy class and static files to update package directory!'''
        os.chdir(pkgDir)
        if not os.path.exists('manage'):
            os.mkdir('manage')
        os.chdir(os.path.join(pkgDir,'manage'))
        os.mkdir(self.projName)
        for i in javaList:
            iPath = os.path.dirname(i)
            fullPath = os.path.join(self.projName,'WEB-INF','classes',iPath[5:])
            if not os.path.exists(fullPath):
                os.makedirs(fullPath)
            javaName = os.path.basename(i[:-5])
            javaPath = os.path.dirname(i)[5:]
            srcBase = os.path.join(codePath,'webapp','WEB-INF','classes')
            src = os.path.join(srcBase,i[5:-5]+'.class')
            dstBase = os.path.join(pkgDir,'manage',self.projName,'WEB-INF','classes')
            dst = os.path.join(dstBase,i[5:-5]+'.class')
            
            '''copy internal class file'''
            curList = os.listdir(os.path.join(srcBase,javaPath))
            inClass = javaName + '$'
            for a in curList: 
                if inClass in a:
                    inPat = re.compile('.*%s\$(.*)\.class$' %javaName)
                    inMat = inPat.search(a)
                    inClassName = javaName + '$' + inMat.group(1) + '.class'
                    insrc = os.path.join(srcBase,os.path.dirname(i[5:-5]),inClassName)
                    indst = os.path.join(dstBase,os.path.dirname(i[5:-5]),inClassName)
                    shutil.copy(insrc,indst)
            try:
                shutil.copy(src, dst)
            except IOError:
                print '文件不存在或已删除:',src
            
        for i in staticList:
            statPath = os.path.dirname(i)
            dstDir = os.path.join(self.projName,statPath[7:])
            if len(statPath[7:]) != 0 and not os.path.exists(dstDir):
                os.makedirs(dstDir)
            staticName = os.path.basename(i)
            src = os.path.join(codePath,i)
            dst = os.path.join(pkgDir,'manage',self.projName,i[7:])
            try:
                shutil.copy(src, dst)
            except IOError:
                print '%s不存在或已删除!' %src
                
        '''copy jar libs to update dircrtory'''
        srcJarDir = os.path.join(codePath,'webapp','WEB-INF','lib')
        dstJarDir = os.path.join(pkgDir,'manage',self.projName,'WEB-INF','lib')
        os.chdir(srcJarDir)        
        for i in os.listdir('.'):
            fInfo = os.stat(i)
            mTime = time.strftime('%Y%m%d%H%M', time.localtime(fInfo.st_mtime))
            if int(mTime) >= upTime:
                try:
                    src = os.path.join(srcJarDir,i)
                    dst = os.path.join(dstJarDir,i)
                    if not os.path.exists(dstJarDir):
                        try:
                            os.makedirs(dstJarDir)
                        except:
                            print "创建lib目录失败!"
                    shutil.copy(src, dst) 
                except:
                    print "复制jar包失败：%s" %i
                                    
def cpCdn():
    '''Copy static files to res project!'''
    os.chdir(pkgDir)
    for i in os.listdir('manage'):
        src = os.path.join('manage',i,'cdn')
        dst = os.path.join('res','res_%s' %cf.get(i,'appname'))
        if os.path.exists(src):
            shutil.copytree(src,dst)
    shutil.copy(os.path.join(exePath,'onemovi.conf'),'.')
    
def compressCdn():
    '''Compress static files'''
    gulpCmd = os.path.join(exePath,'gulp','node_modules','bin','gulp')
    cdnDir = os.path.join(exePath,'gulp','dev')
    cdnDst = os.path.join(exePath,'gulp','dest')
    try:
        print '清空源表态文件目录...'
        shutil.rmtree(os.path.join(cdnDir,'res'))
        shutil.rmtree(os.path.join(cdnDst,'res'))
    except WindowsError:
        pass
    os.chdir(pkgDir)
    if 'res' in os.listdir(pkgDir):
        try:
            shutil.copytree('res',os.path.join(cdnDir,'res'))
            os.chdir(os.path.join(exePath,'gulp'))
            print '压缩表态文件...'
            os.system('gulp build')
        except:
            print "静态资源压缩出错!"
        try:
            os.chdir(pkgDir)
            shutil.rmtree('res')
            shutil.copytree(os.path.join(cdnDst,'res'),'res')
        except:
            print "静态文件复制到更新包出错！"
            pass
    
if __name__ == '__main__':
    '''main line'''
    (inputMain,inputSrv,inputAll) = inputProj()
    Compile()
    pkgDir = mkPkgDir()
    for i in inputAll:
        a = pkgMake(i)
        a.svnVer()
    cpCdn()
    compressCdn()
    raw_input('更新包提取完成,请确认后按回车键退出...')
    exit(0)
    